package org.jeecg.modules.workorder.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.cusstyle.entity.CusStyleInfo;
import org.jeecg.modules.cusstyle.service.ICusStyleInfoService;
import org.jeecg.modules.prodentry.entity.ProdEntry;
import org.jeecg.modules.prodentry.service.IProdEntryService;
import org.jeecg.modules.workorder.entity.WorkingOrder;
import org.jeecg.modules.workorder.entity.WorkingOrderRecord;
import org.jeecg.modules.workorder.service.IWorkingOrderRecordService;
import org.jeecg.modules.workorder.service.IWorkingOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 生产记录查询
 * @Date:   2021-09-09
 * @Version: V1.0
 */
@Api(tags="生产记录查询")
@RestController
@RequestMapping("/workingOrderRecord")
@Slf4j
public class WorkingOrderRecordController extends JeecgController<WorkingOrderRecord, IWorkingOrderRecordService>{
		
	@Autowired
	private IWorkingOrderRecordService workingOrderRecordService;
	
	@Autowired
	private IWorkingOrderService workingOrderService;
	
	@Autowired
	private IProdEntryService prodEntryService;
	
	@Autowired
	private ICusStyleInfoService cusStyleInfoService;
	
	/**
	 * 生产跟单-分页列表查询
	 *
	 * @param productionOrderInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "生产跟单-分页列表查询")
	@ApiOperation(value="生产跟单-分页列表查询", notes="生产跟单-分页列表查询")
	@GetMapping(value = "/rootList")
	@PermissionData(pageComponent="prodOrder/ProductionOrderInfoList")
	public Result<?> queryPageList(WorkingOrderRecord workingOrderRecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String hasQuery = req.getParameter("hasQuery");
		
        if(hasQuery != null && "true".equals(hasQuery)){
            QueryWrapper<WorkingOrderRecord> queryWrapper =  QueryGenerator.initQueryWrapper(workingOrderRecord, req.getParameterMap());
            
            List<WorkingOrderRecord> list = workingOrderRecordService.queryTreeListNoPage(queryWrapper);
            IPage<WorkingOrderRecord> pageList = new Page<>(1, 20, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        }else{
            QueryWrapper<WorkingOrderRecord> queryWrapper = QueryGenerator.initQueryWrapper(workingOrderRecord, req.getParameterMap());
            
            Page<WorkingOrderRecord> page = new Page<WorkingOrderRecord>(pageNo, pageSize);
            IPage<WorkingOrderRecord> pageList = workingOrderRecordService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
	}

	 /**
      * 获取子数据
      * @param productionOrderInfo
      * @param req
      * @return
      */
	@AutoLog(value = "生产工单-获取子数据")
	@ApiOperation(value="生产工单-获取子数据", notes="生产工单-获取子数据")
	@GetMapping(value = "/childList")
	public Result<?> queryPageList(WorkingOrderRecord workingOrderRecord,HttpServletRequest req) {
		QueryWrapper<WorkingOrderRecord> queryWrapper = QueryGenerator.initQueryWrapper(workingOrderRecord, req.getParameterMap());
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		Page<WorkingOrderRecord> page = new Page<WorkingOrderRecord>(1, 20);
        IPage<WorkingOrderRecord> pageList = workingOrderRecordService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

    /**
      * 批量查询子节点
      * @param parentIds 父ID（多个采用半角逗号分割）
      * @return 返回 IPage
      * @param parentIds
      * @return
      */
	@AutoLog(value = "生产工单-批量获取子数据")
    @ApiOperation(value="生产工单-批量获取子数据", notes="生产工单-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result<?> getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<WorkingOrderRecord> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            Page<WorkingOrderRecord> page = new Page<WorkingOrderRecord>(1, 20);
            IPage<WorkingOrderRecord> pageList = workingOrderRecordService.page(page, queryWrapper);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }
	
	/**
	 *   添加
	 *
	 * @param productionOrderInfo
	 * @return
	 */
	@AutoLog(value = "生产工单-添加")
	@ApiOperation(value="生产工单-添加", notes="生产工单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody WorkingOrderRecord workingOrderRecord) {
		workingOrderRecordService.save(workingOrderRecord);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param productionOrderInfo
	 * @return
	 */
	@AutoLog(value = "生产工单-编辑")
	@ApiOperation(value="生产工单-编辑", notes="生产工单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody WorkingOrderRecord workingOrderRecord) {
		workingOrderRecordService.updateById(workingOrderRecord);
		return Result.OK("编辑成功!");
	}
	
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "生产工单-通过id删除")
	@ApiOperation(value="生产工单-通过id删除", notes="生产工单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		workingOrderRecordService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "生产工单-批量删除")
	@ApiOperation(value="生产工单-批量删除", notes="生产工单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.workingOrderRecordService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "生产工单-通过id查询")
	@ApiOperation(value="生产工单-通过id查询", notes="生产工单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		WorkingOrderRecord workingOrderRecord = workingOrderRecordService.getById(id);
		if(workingOrderRecord == null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(workingOrderRecord);
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@PostMapping(value = "/queryList")
	public Result<?> queryList(@RequestBody JSONObject params) {
    	//LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String storeBy = params.getString("storeBy");
		if(storeBy == null || "".equals(storeBy)) {
			return Result.error("未找到对应数据");
		}
		WorkingOrderRecord workingOrderRecord = new WorkingOrderRecord();
		Map<String, String[]> map = new HashMap<>();
        QueryWrapper<WorkingOrderRecord> queryWrapper =  QueryGenerator.initQueryWrapper(workingOrderRecord, map);
        queryWrapper.eq("receive_by", storeBy);
        queryWrapper.eq("store_status", "1");
		List<WorkingOrderRecord> list = workingOrderRecordService.queryTreeListNoPage(queryWrapper);
		if(list == null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(list);
	}
	
	
	/**
	 *  批量交收
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "生产工单-批量交收")
	@ApiOperation(value="生产工单-批量交收", notes="生产工单-批量交收")
	@PostMapping(value = "/batchSettlement")
	@Transactional
	public Result<?> batchSettlement(@RequestBody JSONObject jsonObject) {
		String sendBy = jsonObject.getString("sendBy");
		String sendDept = jsonObject.getString("sendDept");
		String receiveBy = jsonObject.getString("receiveBy");
		String receiveDept = jsonObject.getString("receiveDept");
		Integer workOrderType = getWorkOrderType(jsonObject.getString("type"));
		String jsonString = JSONArray.toJSONString(jsonObject.get("data"));
		JSONArray jsonArray = JSONArray.parseArray(jsonString);
		Date now = new Date();//当前时间

		System.out.println("receiveDept===========1======="+receiveDept);
		if(jsonArray != null && jsonArray.size() > 0) {

			System.out.println("receiveDept======2============"+receiveDept);
			long current = System.currentTimeMillis();
			String won = "WON-" + current;//操作流水号
			String pon = "PON-" + current;//操作流水号
			for(int i = 0; i<jsonArray.size(); i++) {
				String str = JSONArray.toJSONString(jsonArray.get(i));
				JSONObject obj = JSONObject.parseObject(str);
				String id = obj.getString("id");//working_order_record表的主键ID

				System.out.println("receiveDept=========3========="+receiveDept);
				if(id != null && !"".equals(id)) {
					WorkingOrderRecord workingOrderRecord = new WorkingOrderRecord();
					workingOrderRecord.setSendBy(sendBy);//发送人
					workingOrderRecord.setSendDept(sendDept);//发送部门
					workingOrderRecord.setSendTime(now);//发送时间
					workingOrderRecord.setReceiveBy(receiveBy);//接收人
					workingOrderRecord.setReceiveDept(receiveDept);//接收部门
					workingOrderRecord.setReceiveTime(now);//接收时间
					workingOrderRecord.setWorkOrderType(workOrderType);//单类型
					workingOrderRecord.setCount(obj.getInteger("count"));//数量
					workingOrderRecord.setNoAttritionWeight(obj.getBigDecimal("noAttritionWeight"));//不计耗重
					workingOrderRecord.setGoldWeight(obj.getBigDecimal("goldWeight"));//净金重
					workingOrderRecord.setSilverModelWeight(obj.getBigDecimal("silverModelWeight"));//净银重
					workingOrderRecord.setWaxModelWeight(obj.getBigDecimal("waxModelWeight"));//蜡重
					workingOrderRecord.setPureStoneWeight(obj.getBigDecimal("pureStoneWeight"));//石重
					workingOrderRecord.setWithStoneWeight(obj.getBigDecimal("withStoneWeight"));//连石重
					workingOrderRecord.setOtherAccessoryWeight(obj.getBigDecimal("otherAccessoryWeight"));//其他配件重
					workingOrderRecord.setAccessoryCount(obj.getInteger("accessoryCount"));//配件数
					workingOrderRecord.setOriginalWeight(obj.getBigDecimal("originalWeight"));//原重量
					workingOrderRecord.setDifference(obj.getBigDecimal("difference"));//差额
					workingOrderRecord.setAttritionRate(obj.getBigDecimal("attritionRate"));//耗率
					workingOrderRecord.setGate(obj.getBigDecimal("gate"));//水口或链尾
					workingOrderRecord.setGiveAttrition(obj.getBigDecimal("giveAttrition"));//给耗
					workingOrderRecord.setProcedureUnitPrice(obj.getBigDecimal("procedureUnitPrice"));//单价工费（工序）
					workingOrderRecord.setProcedureTotalPrice(obj.getBigDecimal("procedureTotalPrice"));//总工费（工序）
					workingOrderRecord.setRemark(obj.getString("remark"));//备注
					workingOrderRecord.setWorkNum(obj.getString("workNum"));//工单号
					workingOrderRecord.setWorkingOrderId(obj.getString("workingOrderId"));//工单ID
					workingOrderRecord.setPn(obj.getString("pn"));//拆分页
					workingOrderRecord.setSn(won);//操作流水号
					workingOrderRecord.setStoreStatus(1);//状态
					workingOrderRecord.setParentId(id);//父ID
					workingOrderRecordService.addWorkingOrderRecord(workingOrderRecord);
					
					UpdateWrapper<WorkingOrderRecord> updateWorkingOrderRecord = new UpdateWrapper<>();
					updateWorkingOrderRecord.set("has_child", "1");
					updateWorkingOrderRecord.set("store_status",null);
					updateWorkingOrderRecord.eq("id",id);
					workingOrderRecordService.update(updateWorkingOrderRecord);
					
					
					UpdateWrapper<WorkingOrder> updateWorkingOrder = new UpdateWrapper<>();
					updateWorkingOrder.set("store_by",receiveBy);
					updateWorkingOrder.set("store_dept",receiveDept);
					updateWorkingOrder.set("work_order_type", workOrderType);
					updateWorkingOrder.set("curr_working_order_record_id", workingOrderRecord.getId());
					updateWorkingOrder.eq("id",workingOrderRecord.getWorkingOrderId());
					workingOrderService.update(updateWorkingOrder);
					if("A02A04A13".equals(receiveDept)) {//接收部门是成品部,则写一条入仓记录到成品仓
						String workingOrderId = obj.getString("workingOrderId");
						WorkingOrder wo = this.workingOrderService.getById(workingOrderId);
						String styleCusInfoId = wo.getStyleCusInfoId();
						CusStyleInfo cusStyleInfo = this.cusStyleInfoService.getById(styleCusInfoId);
						ProdEntry prodEntry = new ProdEntry();
						prodEntry.setProdActionType(1);//操作类型 1成品入仓
						prodEntry.setSn(pon);//操作流水号
						prodEntry.setSendPerson(sendBy);//发出员工
						prodEntry.setSendTime(now);//发出时间
						prodEntry.setReceiveStorage("1474578813781348354");//接收的成品仓库
						prodEntry.setReceiveTime(now);//接收时间
						prodEntry.setWorkNum(obj.getString("workNum"));//工单号
						prodEntry.setPn(obj.getString("pn"));//拆分页
						prodEntry.setOrderInfoId(wo.getOrderInfoId());//订单号
						prodEntry.setCustomerInfoId(cusStyleInfo.getCustomerInfoId());//客户
						prodEntry.setStyleCusInfoId(styleCusInfoId);//款号
						prodEntry.setKarat(cusStyleInfo.getGoldKaratId());//成色
						prodEntry.setCount(obj.getInteger("count"));//数量
						prodEntry.setGoldWeight(obj.getBigDecimal("goldWeight"));//净金重
						prodEntry.setPureStoneWeight(obj.getBigDecimal("pureStoneWeight"));//石重
						prodEntry.setWithStoneWeight(obj.getBigDecimal("withStoneWeight"));//连石重
						prodEntry.setUnitPrice(cusStyleInfo.getUnitPrice());//单价金额(￥)
						
						prodEntryService.save(prodEntry);
					}
				}
			}
			return Result.ok("批量交收成功！");
		} else {
			return Result.error("操作失败，请选择要交收的工单数据！");
		}
	}
	
	private Integer getWorkOrderType(String type) {
		//3移交单、4生产单、5回收单
		if("1".equals(type)) {
			return 3;
		} else if("2".equals(type)) {
			return 4;
		} else if("3".equals(type)) {
			return 5;
		}
		return 0;
	}
}
